package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.PeachBlossomAudioApi;
import com.tanhua.dubbo.server.pojo.Audio;
import com.tanhua.server.vo.AudioVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class PeachBlossomVoiceService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserService userService;
    @Value("${tanhua.sso.url}")
    private String ssoUrl;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference(version = "1.0.0")
    private PeachBlossomAudioApi peachBlossomAudioApi;
    private static final ObjectMapper MAPPER = new ObjectMapper();


    /**
     * 业务层实现功能:桃花传音之发送语音
     *
     * @param file
     * @return
     * @throws IOException
     */
    public Boolean peachblossomPut(MultipartFile file) throws IOException {
        String url = ssoUrl + ":18080/pic/upload";
        User userToken = UserThreadLocal.get();
        Long userId = userToken.getId();
        //上传语音文件
        ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }

            @Override
            public long contentLength() {
                return file.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("file", fileAsResource);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, headers);
        //发起调用
        Object object = restTemplate.postForObject(url, requestEntity, Object.class);
        System.out.println(object);
        PicUploadResult picUploadResult = BeanUtil.copyProperties(object, PicUploadResult.class);
        //System.out.println(picUploadResult);
        //TODO
        if (StringUtils.isEmpty(picUploadResult.getName())) {
            return false;
        }
        Audio audio = new Audio();
        audio.setUserId(userId);
        audio.setAudioUrl(picUploadResult.getName());
        //返回保存音频的结果
        Boolean result = peachBlossomAudioApi.saveAudio(audio);
        return result;


    }

    /**
     * 业务层实现功能:桃花传音之接收语音
     *
     * @return
     */
    public AudioVo receiveVoice() {
        AudioVo audioVo = new AudioVo();
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Audio audio = peachBlossomAudioApi.receiveVoice(userId);
        if (audio == null) {
            audioVo = new AudioVo();
            audioVo.setRemainingTimes(0);
            //获取用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            //填充用户信息
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            audioVo.setAge(userInfo.getAge());
            audioVo.setAvatar(userInfo.getLogo());
            audioVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            audioVo.setNickname(userInfo.getNickName());
            return audioVo;
        }
        audioVo.setId(audio.getUserId().intValue());
        audioVo.setCreateDate(StrUtil.toString(audio.getCreated()));
        audioVo.setSoundUrl(audio.getAudioUrl());
        //获取用户信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", audio.getUserId());
        //填充用户信息
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        audioVo.setAge(userInfo.getAge());
        audioVo.setAvatar(userInfo.getLogo());
        audioVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        audioVo.setNickname(userInfo.getNickName());
        audioVo.setRemainingTimes(audio.getCount());//TODO 剩余次数
        //返回桃花传音的信息
        return audioVo;
    }
}
